<!DOCTYPE html>
<html lang="zh-cn">
	<head>
        <title>数据交换单元管理</title>
		<#include "../../../__ref_common.ftl" parse=true/>
		<link rel="stylesheet" href="${mvcPath}/dacp-view/datastash/workshop/unit_list/css/model_dev.css">
		<script src="${mvcPath}/dacp-res/js/cMessage.js"></script>

	<style type="text/css">
		
	.control-sidebar.control-sidebar-open{
		max-width: 400px;
		min-width: 400px;
		heighdt:calc(100% - 75px);
	}
	.control-sidebar {
		background: #e0e0e0;
		position: absolute;
		margin-top: 35px;
		z-index: 1010;
		box-shadow: 0 1px 3px rgba(0,0,0,.3);
	}
	.control-sidebar {
		top: 0;
		bottom: 0;
		padding: 0;
		right: 0;
		max-width: 0;
		overflow: hidden;
		-moz-transform: translate(0,0);
		-webkit-transform: translate(0,0);
		-o-transform: translate(0,0);
		-ms-transform: translate(0,0);
		transform: translate(0,0);
		background-color: #FFF;
		border: 0 solid #ffb34b;
		-webkit-transition: max-width 0.25s linear 0s;
		-o-transition: max-width 0.25s linear 0s;
		transition: max-width 0.25s linear 0s;
	}

.base-info {
	padding: 20px;
}
.base-info .item{
	display: inline-block;
	margin-bottom: 10px;
	width: 100%;
}
.base-info .label{
	width:100px;
	text-align:right;
	display:block; 
	float:left;
	color: #99a9bf;
}
.base-info .text{
	display:block;
	line-height: 20px;
}

.close-sidebar {
	float: right;
	border: 0;
}
div#list1 {
	height: calc(100% - 50px);
	overflow: auto;
}
			div#list2 {
	height: calc(100% - 50px);
	overflow: auto;
}
.import_file .el-upload{
    width:100%;
}
.import_file .el-upload .el-upload-dragger{
    width:100%;
}
.import_file .btn_group{
    width:100%;
    margin-top:10px;
    text-align:center;
}

	</style>
	</head>
	<body >
	<#include "__table_piece.ftl" parse=true/>
		<div id="main">
			<elx-main>
			    <div id="content" class="layout">
			        <div class="elx-tab-frame">
				        <elx-tabs type="border-card" v-model="tabActiveIndex" closable @tab-remove="removeTab">
				            <div class="title" slot="title" @click="backMain">
				                <span v-html="title"></span>
				            </div>
				            <div v-show="tabActiveIndex=='nothing'">
				                <elx-tree :data="treeData" :current-node-key="currentNodeKey" :default-expanded-keys="defaultExpandedKeys" :props="defaultProps" @node-click="nodeClick"  @right-click="rightClick"></elx-tree>
					            <div class="program-content">
				                    <div class="content-header">
				                        <div class="proTotal">
				                            <span class="uex-icon-menu-card"></span>
					                        <span v-html="$t('单元共')"></span>
					                        <span class="num">{{totalElements}}</span>
					                        <span v-html="$t('个')"></span>
				                        </div>
				                        <el-form :inline="true" :model="filter" class="demo-form-inline">
                                            <el-form-item  label="单元编码" >
                                                <el-input v-model="filter.unitCode"  placeholder="请填写单元编码"></el-input>
                                            </el-form-item>
                                            <el-form-item  label="单元名称" >
                                                <el-input v-model="filter.label"  placeholder="请填写单元名称"></el-input>
                                            </el-form-item>
                                            <el-form-item  label="单元类型"   >
                                                <el-select v-model="filter.unitType"    placeholder="单元类型">
                                                    <el-option v-for="item in unitTypes"   :label="item.name" :value="item.value"></el-option>
                                                </el-select >
                                            </el-form-item>
                                            <el-form-item  label="状态"   >
                                                <el-select v-model="filter.state"    placeholder="状态">
                                                    <el-option v-for="item in states"   :label="item.name" :value="item.value"></el-option>
                                                </el-select >
                                            </el-form-item>
										    <el-form-item class="button-group">
                                                <el-button @click="search">{{$t('查询')}}</el-button>
										        <el-button @click="add">{{$t('新建')}}</el-button>
										    </el-form-item>
										</el-form>
										<div class="pull-right">
										    <span class="uex-icon uex-icon-menu-list" @click="showType=2"></span>
										    <span class="uex-icon uex-icon-menu-card" @click="showType=1"></span>
										</div>
				                    </div>
				                    <div class="list-content"> 
						                <div class="pro-list"  v-loading="loading" id="list1" v-show="showType == '1'" :style="{'overflow': listOverflow}">
						                <template v-if="units && units.length>0">
							                <elx-item-list ref="elxItemList" :data = 'units' :props = "listDefaultProps"
							                     :icon = "'uex-icon-table'"
							                     @dblclick="editItem"
							                     @click="selectModel"
							                     @delete="deleteItem"
							                     @edit="editItem"
							                     :class="isSelected"
							                     @right-click="listRightClick"
							                     style="width:100%;height:100%">

                                                <template scope="scope" slot="operate">
                                                    <ul>
                                                        <li @click.stop.prevent="editItem(scope.data)">
                                                            <span class="uex-icon-field-blood-analyse"></span>
                                                            <span v-html="$t('编辑')"></span>
                                                        </li>

                                                        <li v-if="scope.data.state=='1'" @click.stop.prevent="offlineItem(scope.data)">
                                                            <span class="uex-icon-field-blood-analyse"></span>
                                                            <span v-html="$t('下线')"></span>
                                                        </li>
                                                        <li @click.stop.prevent="deleteItem(scope.data)">
                                                            <span class="uex-icon-field-blood-analyse"></span>
                                                            <span v-html="$t('删除')"></span>
                                                        </li>
                                                    </ul>
                                                </template>
							                </elx-item-list>
							                </template>
						                	<template v-else>
												<elx-placeholder ></elx-placeholder>
											</template>
						                </div>
						               <div class="pro-list" id="list2" v-loading="loading" v-show="showType == '2'">
						               		<div id="tabpanel">
												<template v-if="units && units.length>0">
								                    <elx-table-list v-for="data in units"  :item="data"  v-on:offline="offlineItem"   v-on:edit="editItem" v-on:delete="deleteItem" v-on:alter="alterItem" v-on:dblclick="editItem"></elx-table-list>
												</template>
												<template v-else>
													<elx-placeholder ></elx-placeholder>
												</template>
											</div>
						                </div>
						                
						                <div class="page paginationCommon" v-show="totalElements > 50">
			       							 <el-pagination  @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="filter.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalElements"></el-pagination>
			   							</div>
	
			   							<div class="control-sidebar" :class="isOpen()" id="log-stash-panel">
											<div class="base-info" >
												<el-button :plain="true" icon="close" class="close-sidebar"  @click="closeSidebar"></el-button>
												<div class="item">
													<span class="label" v-html="$t('编码')+':'"></span>
													<span class="text" v-html="selectedItem.unitCode"></span>
												</div>
												<div class="item">
													<span class="label" v-html="$t('名称')+':'"></span>
													<span class="text" v-html="selectedItem.label"></span>
												</div>
												<div class="item">
													<span class="label" v-html="$t('单元类型')+':'"></span>
													<span class="text" v-html="unitTypeFormatter(selectedItem)"></span>
												</div>
                                                <div class="item">
                                                    <span class="label" v-html="$t('批次周期')+':'"></span>
                                                    <span class="text" v-html="selectedItem.batchType"></span>
                                                </div>
                                                <div class="item">
                                                    <span class="label" v-html="$t('批次偏移量')+':'"></span>
                                                    <span class="text" v-html="selectedItem.batchOffset"></span>
                                                </div>
                                                <div class="item">
                                                    <span class="label" v-html="$t('批次号')+':'"></span>
                                                    <span class="text" v-html="selectedItem.batchNo"></span>
                                                </div>
                                                <div class="item">
                                                    <span class="label" v-html="$t('批次步进')+':'"></span>
                                                    <span class="text" v-html="selectedItem.batchStep"></span>
                                                </div>
                                                <div class="item">
                                                    <span class="label" v-html="$t('版本')+':'"></span>
                                                    <span class="text" v-html="selectedItem.version"></span>
                                                </div>
                                                <div class="item">
                                                    <span class="label" v-html="$t('创建用户')+':'"></span>
                                                    <span class="text" v-html="selectedItem.createUser"></span>
                                                </div>
                                                <div class="item">
                                                    <span class="label" v-html="$t('状态')+':'"></span>
                                                    <span class="text" v-html="stateFormatter(selectedItem)"></span>
                                                </div>
											</div>
			   							</div>
		   							</div>
					            </div>
				            </div>
				            <el-tab-pane v-show="tabActiveIndex!='nothing'&&tabActiveIndex == item.name" v-for="(item, index) in tabData" :label="item.label" :name="item.name">
				                <iframe :src="item.url"></iframe>
                            </el-tab-pane>
				        </elx-tabs>
			        </div>
			    </div>
			</elx-main>
		</div>
		<script>
			var getData = function(vm){
                    var _self = vm;
                    axios.get(_contextPath + '/open/datastash',{
                        params: {
                            state: _self.filter.state,
                            unitType: _self.filter.unitType,
                            label: _self.filter.label,
                            unitCode: _self.filter.unitCode,
                            pageNum: _self.filter.pageNum,
                            pageSize: _self.filter.pageSize
                        }
                    })
					.then(function (response) {
						var data = response.data;
						if (data) {
							_self.units = data.content||[];
							_self.totalElements = data.totalElements||0;
						}
					})
					.catch(function (error) {
						console.log(error);
					});
			};
			
			var getAllMembers = function(vm){
				$.ajax({
					type : "post",
					url: '${mvcPath}/open/metamodel/team/'+vm.curTeamId+'/allMembers',
					async : false,
					dataType: 'json',
					success: function(data) {
						vm.teamMembers = data || [];
					},
					error: function (data) {
						vm.teamMembers = [];
					}
				});
			};
			
			var gTeamId = "";
			var gMemberId="";
			$.ajax({
				type : "get",
				url: "${mvcPath}/dataps/user/member",
				async : false,
                dataType:'json',
				success: function(data){
					gTeamId = data.teamId;
					gMemberId = data.id;
				}
			});
		var getFirstLeafId = function(treeData) {
			var result = '';
			var procGetFirstLeafId = function(treeData) {
				if(treeData.children && treeData.children.length > 0) {
					procGetFirstLeafId(treeData.children[0]);
				} else {
					result = treeData.id;
				}
			};
			procGetFirstLeafId(treeData);
			return result;
			
		};
		//第一层全部展开
		var getTreeFirstLvlId = function(vue,treeData) {
			var result = [];
			if(treeData && treeData.children && treeData.children.length>0) {
				for(var i=0;i<treeData.children.length;i++) {
					var firstLvlNode = treeData.children[i];
					if(firstLvlNode) {
						if(i==0){
							vue.currentNodeKey = firstLvlNode.id;
						}
						result.push(firstLvlNode.id);
					}
				}
			}
			return result;
		};
		//第二层全部展开
		var getTreeSecondLvlId = function(vue,treeData) {
			var result = [];
			if(treeData && treeData.children && treeData.children.length>0) {
				for(var i=0;i<treeData.children.length;i++) {
					var firstLvlNode = treeData.children[i];
					if(firstLvlNode) {
						if(i==0){
							vue.currentNodeKey = firstLvlNode.id;
						}
					}
					if(firstLvlNode && firstLvlNode.children && firstLvlNode.children.length > 0) {
						for(var j=0;j<firstLvlNode.children.length;j++) {
							var secondLvlNode = firstLvlNode.children[j];
							if(secondLvlNode) {
								result.push(secondLvlNode.id);
							}
						}
					}
				}
			}
			return result;
		};
		var programVm = new Vue({
		    el: '#main',
		    i18n: i18n,
		    data: function(){
		        return {
                    loading: false,
                    treeData: [],
                    currentNodeKey: '',
                    defaultExpandedKeys: [],
                    tabData: [],
                    curArchId: '',
                    isCurArchIdLeaf: false,
                    curSubjectId: '',
                    curLvlId: '',
                    curDsId: '',
                    curTeamId: gTeamId,
                    curMemberId: gMemberId,
                    handoverDialog: false,
                    handoverForm: {
                        num: '0',
                        memberId: '',
                        oldMemberId: '',
                        tableId: '',
                        teamId: gTeamId
                    },
                    teamMembers: [],
                    formLabelWidth: '100px',
                    tabActiveIndex: "nothing",
                    title: '单元管理',
                    defaultProps: {
                        children: 'children',
                        label: 'label'
                    },
                    currentPage: 1,
                    totalElements: 0,
                    filter: {
                        unitCode: '',
                        label: '',
                        unitType: '',
                        state: '',
                        pageSize: 50,
                        sortActive: 0,
                        operActive: 0,
                        label: '',
                        tabDensLvl: '',
                        states: '',
                        sortColumn: "lastupd",
                        desc: "",
                        pageNum: 0
                    },
                    units:[],
                    unitTypes: unitTypes,
                    states: states,
                    showType: "1",
                    listOverflow: 'auto',
                    showSideBar: false,
                    sideBarTimeout: null,
                    selectedItem: {},
                    listDefaultProps: {
                        name: 'name',
                        cnName: 'label'
                    }
                }
                },
		    methods: {
		    	listRightClick: function(data){
		    		data.isCopy = false;
		    		data.isCut = false;
		    		data.isPaste = false;
		    		if(this.curMemberId != data.memberId || data.state != 'NEW') {
		    			data.isDelete = false;
		    			data.isEdit = false;
		    		}
		    	},
	            getCatetoryTree:function(){
	            	var _self = this;
	                $.ajax({
	                    type : "get",
	                    url: "${mvcPath}/open/metamodel/getTeamArchTree",
	                    data:{
	                    	teamId:_self.curTeamId,
	                    },
	                    async : false,
	                    dataType: 'json',
	                    success: function(data) {
	                    	console.log(data);
	                    	_self.defaultExpandedKeys = getTreeFirstLvlId(_self,data);
	                    	_self.treeData = data.children;
	                    	_self.$nextTick(function () {
	                          })
	                    },
	                    error: function (data) {
	                    }
	                });
	            },
		    	removeTab: function(name) {
		            var _self = this;
		            var _filterTabData = [];
		            _.map(this.tabData, function(tab) {
		              if (tab.name === name) {
		                var _index = _self.tabData.indexOf(tab);
		                var _nextTab = _self.tabData[_index + 1] || _self.tabData[_index - 1];
		                _self.tabActiveIndex = _nextTab ? _nextTab.name : null;
		              }else{
		            	  _filterTabData.push(tab)
		              }
		            });
		            this.tabData = _filterTabData
		    	},
		    	nodeClick: function(node){
		    		var _self = this;
		    		console.log(node);
		    		_self.curArchId = node.data.id;
					_self.curLvlId = '';
					_self.curSubjectId = '';
		    		if(!(node.data.children && node.data.children.length > 0)) {
		    			_self.isCurArchIdLeaf = true;
		    			$.ajax({
		    				type : "get",
		    				url: "${mvcPath}/open/metamodel/getSubjectInfoByArchId",
		    				data: {archId:_self.curArchId},
		    				async : false,
		    				dataType:'json',
		    				success: function(data){
		    					_self.curLvlId = data["lvl"];
		    					_self.curSubjectId = data["topic"];
		    				}
		    			});
		    		} else {
		    			_self.isCurArchIdLeaf = false;
		    		}
		    		getData(_self);
		    	},
		    	rightClick: function(node){
		    			node.data.isDelete = false;
		    			node.data.isAdd = false;
		    			node.data.isEdit = false;
		    	},
				renameNode: function(node){
					console.log(node);
		    	},
                deleteItem:function(row){
                    var _self=this;
                    _self.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                        type: 'warning'
                    }).then(function() {
                        axios.post(_contextPath + '/open/datastash/unit/' + row.id + '/delete')
                                .then(function (response) {
                                    if (response.data.success) {
                                        _self.$alert('删除成功！', '提示', {
                                            confirmButtonText: '确定'
                                        });
                                        getData(_self);
                                    } else {
                                        _self.$alert('删除失败！', '提示', {
                                            confirmButtonText: '确定'
                                        });
                                    }
                                })
                                .catch(function (error) {

                                });

                    }).catch(function() {
                        self.$notify({
                            type: 'success',
                            title: '已取消删除！',
                            duration: 300
                        });0
                    });
                },

                editItem: function(item){
                    clearTimeout(this.sideBarTimeout);
                    this.openTab({name:'edit',label:item.label,url:'${mvcPath}/datastash/workshop/unit/'+item.id});
                },
                offlineItem:function (item) {
                    var _self = this;
                    axios.get(_contextPath+'/open/datastash/unit/offlineApply/'+item.id,{})
						.then(function (response) {
							var data = response.data;
							if(data.success) {
								_self.$notify({
									type: 'success',
									title: '成功！',
									message: '下线成功',
									duration: 3000
								});
								getData(_self);
							}else {
								_self.$notify({
									type: 'error',
									title: '下线失败！',
									message: data.msg,
									duration: 3000
								});
							}

						})
						.catch(function (error) {
							console.log(error);
						});
                },
		        openTab:function(data) {
		        	var _self = this;
		        	var _filterTabData = [];
		        	this.tabActiveIndex = this.tabData>0?this.tabData[this.tabData.length-1].name:this.tabActiveIndex;
		        	this.$nextTick(function(){
		        		_.map(_self.tabData, function(tab) {
		                	if(tab.name === data.name){
		                		_filterTabData.push(tab);
		                	}
		                });
		                if (_filterTabData.length === 0) {
		                	_self.tabData.push(data);
		                	_self.$nextTick(function() {
		                        _self.tabActiveIndex = data.name;
		                    });
		                } else {
		                    _self.tabActiveIndex = _filterTabData[0].name;
		                }
		        	})
		        },
		        backMain: function(){
		        	this.tabActiveIndex = "nothing"
		        },
		        search: function(){
					this.filter.pageNum = 0;
					getData(this);
		        },
				sort: function(type){
					if(type=="default"){
						this.filter.sortActive=0;
						this.filter.operActive=0;
					}else if(type=="LASTUPD"){
						this.filter.operActive=1;
					    this.filter.sortActive=this.filter.sortActive==1?2:1;	
					}
					getData(this);
				},
				handleCurrentChange: function(val){
					this.filter.pageNum = val-1;
					getData(this);
				},
				handleSizeChange: function(size){
				    this.filter.pageSize = size;
				    getData(this);
				},
		        alterItem:function(item) {
					clearTimeout(this.sideBarTimeout);
					var param = "?teamId="+this.curTeamId+"&dsId="+this.curDsId+"&subjectId="+this.curSubjectId;
					item.url = '${mvcPath}/metamodel/table/creator/'+item.id + param+"&opType=alter";
					this.openTab(item);
		        }, 
		        handover: function(data){
		        	getAllMembers(this);
		        	this.handoverDialog = true;
		        	this.handoverForm.oldMemberId = data.memberId;
		        	this.handoverForm.tableId = data.id;
		        },
		        cancel:function(){
    				this.handoverDialog = false;
    			},
		        add: function(){
                    this.openTab({name:'new',label:this.$t('新建'),url:'${mvcPath}/datastash/workshop/unit/creator'});
                    /*if(this.isCurArchIdLeaf) {
                        var param = "?archId=" + this.curArchId+ "&teamId="+this.curTeamId+"&dsId="+this.curDsId+"&subjectId=" + this.curSubjectId + "&lvlId=" + this.curLvlId;
                        this.openTab({name:'new',label:this.$t('新建'),url:'${mvcPath}/metamodel/table/creator'+param});
		        	} else {
	                    this.$notify({
	                        type: 'error',
	                        title: this.$t('警告'),
	                        message: this.$t('新建时')+this.$t('所选模型目录应为最底层目录')+'！'
	                    });
		        	}*/

		        },
		        isOpen: function(){
		        	return this.showSideBar ? 'control-sidebar-open' : '';
		        },
		        getItemDatasource: function(item){
		        	return item.metaDataSource ? item.metaDataSource.label : '';
		        },
		        selectModel: function(item){
		        	var _self = this;
		        	clearTimeout(this.sideBarTimeout);
		        	this.sideBarTimeout = setTimeout(function(){
						if (_self.showSideBar){
							if (_self.selectedItem.id == item.id){
								_self.showSideBar = !_self.showSideBar;
							}else {
								_self.selectedItem = item;
							}
						}else{
							_self.showSideBar = !_self.showSideBar;
							_self.selectedItem = item;
						}
		        	},200)
		        },
		        closeSidebar: function(){
		        	this.showSideBar = false;
		        },
		        isSelected: function(item){
		        	return this.selectedItem.id == item.id ? 'selected' : '';
		        },
		        share: function(){},
		        refreshItemList: function() {
		        	var _self = this;
		        	this.$nextTick(function() {
		        		if (typeof this.$refs['elxItemList'] !== 'undefined') {
		        			this.listOverflow = 'scroll';
		        			this.$nextTick(function() {
		        				_self.$refs['elxItemList'].computeNum();
		        				_self.listOverflow = 'auto';
		        			})
		        		}
		        	})
		        },
				handleChange:function (file, fileList) {
		            this.fileList = fileList.slice(0-this.maxUploadSize);
		        },
				unitTypeFormatter:function(val){
               		 return unitTypeFormatter(val);
				},
                stateFormatter:function(val){
                    return  stateFormatter(val);
                },
				viewUnit:function (val) {
					this.src  ='${mvcPath}/datastash/workshop/unit/'+val.id;
					this.type = "create";
				}
		    },
		    watch: {
		    	tabData: function(val, oldVal){
		    		if(val.length == 0){
		    			this.tabActiveIndex = "nothing"
		    		}
		    	},
		    	showType: function(val,oldVal){
		    	    this.refreshItemList();
		    	}
		    },
		    mounted: function(){
		    	var _self = this;
		    	this.$nextTick(function(){
		    		if (window.top !== window.self) {
		    			_.cMessage.postMessage({frameLoaded: true}, location.origin, parent);
		    		}
		    		_.cMessage.bindReceiveMessage({isExecFunc: true, base: _self})
		    	})
		    },
		    created: function(){
		        this.getCatetoryTree();
		        getData(this);
		    }
		})
		
		</script>
	</body>
</html>